import Toast from 'tdesign-miniprogram/toast/index';
import auth from '../../utils/auth';
import { isTokenExpiredError, handleTokenExpiredError, checkAndHandleAuthError } from '../../utils/auth-error-handler';

const db = wx.cloud.database();

Page({
  data: {
    stats: {
      totalCodes: 0,
      activeCodes: 0,
      usedCount: 0,
      todayUsed: 0
    },
    
    inviteList: [],
    loading: false,
    
    // 编辑弹窗
    showEditDialog: false,
    isEditing: false,
    isSubmitting: false,
    formData: {
      code: '',
      rewardPoints: 100,
      remark: ''
    }
  },

  onLoad() {
    // 检查管理员权限
    if (!this.checkAdminPermission()) {
      return;
    }
    
    this.loadStats();
    this.loadInviteList();
  },

  /**
   * 检查管理员权限
   */
  checkAdminPermission() {
    if (!auth.isLoggedIn()) {
      auth.navigateToLogin('/pages/invite-management/index');
      return false;
    }
    
    const userInfo = auth.getCurrentUser();
    if (!userInfo || userInfo.role !== 'admin') {
      wx.showModal({
        title: '权限不足',
        content: '只有管理员才能访问此页面',
        showCancel: false,
        success: () => {
          wx.navigateBack();
        }
      });
      return false;
    }
    
    return true;
  },

  /**
   * 加载统计信息
   */
  async loadStats() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'invite-management',
        data: {
          action: 'getStats'
        }
      });

      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '邀请管理权限已过期，请重新登录'
      })) {
        return;
      }

      if (result.result.success) {
        this.setData({ stats: result.result.data });
      }
    } catch (error) {
      console.error('加载统计失败:', error);
      
      // 检查异常信息是否包含token过期错误
      if (isTokenExpiredError(error.message)) {
        handleTokenExpiredError({
          customMessage: '邀请管理权限已过期，请重新登录'
        });
      }
    }
  },

  /**
   * 加载邀请码列表
   */
  async loadInviteList() {
    this.setData({ loading: true });

    try {
      const result = await wx.cloud.callFunction({
        name: 'invite-management',
        data: {
          action: 'getList'
        }
      });

      // 检查是否为token过期错误
      if (checkAndHandleAuthError(result, {
        customMessage: '邀请管理权限已过期，请重新登录'
      })) {
        this.setData({ loading: false });
        return;
      }

      if (result.result.success) {
        const list = result.result.data.map(item => ({
          ...item,
          createTimeStr: this.formatTime(item.createTime)
        }));
        this.setData({ inviteList: list });
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.result.message || '加载失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('加载邀请码列表失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加载失败，请重试',
        theme: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 生成邀请码
   */
  onCreateInviteCode() {
    this.setData({
      showEditDialog: true,
      isEditing: false,
      formData: {
        code: '',
        rewardPoints: 100,
        remark: ''
      }
    });
  },

  /**
   * 编辑邀请码
   */
  onEditInviteCode(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showEditDialog: true,
      isEditing: true,
      editingId: item._id,
      formData: {
        code: item.code,
        rewardPoints: item.rewardPoints,
        remark: item.remark || ''
      }
    });
  },

  /**
   * 随机生成邀请码
   */
  onGenerateRandomCode() {
    const code = this.generateRandomCode();
    this.setData({
      'formData.code': code
    });
  },

  /**
   * 生成8位随机邀请码
   */
  generateRandomCode() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 排除容易混淆的字符
    let code = '';
    for (let i = 0; i < 8; i++) {
      code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return code;
  },

  /**
   * 表单输入处理
   */
  onFormCodeChange(e) {
    this.setData({ 'formData.code': e.detail.value.toUpperCase() });
  },

  onFormPointsChange(e) {
    this.setData({ 'formData.rewardPoints': parseInt(e.detail.value) || 0 });
  },

  onFormRemarkChange(e) {
    this.setData({ 'formData.remark': e.detail.value });
  },

  /**
   * 确认创建/编辑
   */
  async onConfirmEdit() {
    const { code, rewardPoints } = this.data.formData;

    // 验证
    if (!this.data.isEditing && !code) {
      // 创建时如果没有填写，自动生成
      this.setData({ 'formData.code': this.generateRandomCode() });
    }

    if (!/^[A-Z0-9]{6,12}$/.test(this.data.formData.code)) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '邀请码必须是6-12位大写字母或数字',
        theme: 'warning'
      });
      return;
    }

    if (!rewardPoints || rewardPoints < 0) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入有效的奖励积分',
        theme: 'warning'
      });
      return;
    }

    this.setData({ isSubmitting: true });

    try {
      const action = this.data.isEditing ? 'update' : 'create';
      const requestData = {
        action,
        data: this.data.formData
      };

      if (this.data.isEditing) {
        requestData.data.id = this.data.editingId;
      }

      const result = await wx.cloud.callFunction({
        name: 'invite-management',
        data: requestData
      });

      if (result.result.success) {
        Toast({
          context: this,
          selector: '#t-toast',
          message: this.data.isEditing ? '修改成功' : '生成成功',
          theme: 'success'
        });

        this.setData({ showEditDialog: false });
        this.loadStats();
        this.loadInviteList();
      } else {
        Toast({
          context: this,
          selector: '#t-toast',
          message: result.result.message || '操作失败',
          theme: 'error'
        });
      }
    } catch (error) {
      console.error('操作失败:', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '操作失败，请重试',
        theme: 'error'
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  /**
   * 取消编辑
   */
  onCancelEdit() {
    this.setData({ showEditDialog: false });
  },

  /**
   * 弹窗显示/隐藏
   */
  onEditDialogChange(e) {
    this.setData({ showEditDialog: e.detail.visible });
  },

  /**
   * 复制邀请码
   */
  onCopyCode(e) {
    const code = e.currentTarget.dataset.code;
    wx.setClipboardData({
      data: code,
      success: () => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '邀请码已复制',
          theme: 'success'
        });
      }
    });
  },

  /**
   * 切换状态
   */
  async onToggleStatus(e) {
    const { id, status } = e.currentTarget.dataset;
    const statusText = status === 'active' ? '启用' : '禁用';

    wx.showModal({
      title: '确认操作',
      content: `确定要${statusText}该邀请码吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await wx.cloud.callFunction({
              name: 'invite-management',
              data: {
                action: 'toggleStatus',
                data: { id, status }
              }
            });

            if (result.result.success) {
              Toast({
                context: this,
                selector: '#t-toast',
                message: `${statusText}成功`,
                theme: 'success'
              });
              this.loadStats();
              this.loadInviteList();
            } else {
              Toast({
                context: this,
                selector: '#t-toast',
                message: result.result.message || '操作失败',
                theme: 'error'
              });
            }
          } catch (error) {
            console.error('切换状态失败:', error);
            Toast({
              context: this,
              selector: '#t-toast',
              message: '操作失败，请重试',
              theme: 'error'
            });
          }
        }
      }
    });
  },

  /**
   * 删除邀请码
   */
  async onDeleteInviteCode(e) {
    const { id, code } = e.currentTarget.dataset;

    wx.showModal({
      title: '确认删除',
      content: `确定要删除邀请码 ${code} 吗？此操作不可恢复！`,
      confirmText: '确认删除',
      confirmColor: '#e34d59',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await wx.cloud.callFunction({
              name: 'invite-management',
              data: {
                action: 'delete',
                data: { id }
              }
            });

            if (result.result.success) {
              Toast({
                context: this,
                selector: '#t-toast',
                message: '删除成功',
                theme: 'success'
              });
              this.loadStats();
              this.loadInviteList();
            } else {
              Toast({
                context: this,
                selector: '#t-toast',
                message: result.result.message || '删除失败',
                theme: 'error'
              });
            }
          } catch (error) {
            console.error('删除失败:', error);
            Toast({
              context: this,
              selector: '#t-toast',
              message: '删除失败，请重试',
              theme: 'error'
            });
          }
        }
      }
    });
  },

  /**
   * 格式化时间
   */
  formatTime(date) {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hour = String(d.getHours()).padStart(2, '0');
    const minute = String(d.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }
});

